#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   tftp_up_download.sh
# Version:    1.0
# Date:       2013/05/15
# Author:      huijing.hei
# Email:       huijing.hei@cs2c.com.cn
# Summary:     02系统基本功能-04网络服务-02tftp-03上传下载文件
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/05/15
#             - Start tftp service.
# ----------------------------------------------------------------------
# include lib files
if [ -z "$SFROOT" ]
then
    CMDLIB=./
    SFROOT=./
else
    CMDLIB=${SFROOT}/testcases/Network_Service
fi

. ${SFROOT}/lib/Echo.sh
. ${CMDLIB}/lib/Net.sh
. ${SFROOT}/lib/XmlParse.sh

. ${CMDLIB}/setup.sh

# get RHOST, RUSERNAME, PASSWORD from config.xml
DATA_FILE="${SFROOT}/testcases/Network_Service/config.xml"
[ -e $DATA_FILE ] || { echo "$DATA_FILE not find, test end."; exit 1; }

XmlParse ${DATA_FILE}

GetValue REHOST ReHost
GetValue RUSERNAME UserName
GetValue PASSWORD RootPasswd

export RHOST=${REHOST}
export RUSERNAME=${RUSERNAME}
export PASSWORD=${PASSWORD}


setup_env || { echo "setup env failed, test end."; exit 1; }


RC=0
# create temp file, for upload.
TMP_DIR="/tmp/tftp$$"
mkdir -p ${TMP_DIR}

TMP_FILE="tftp_start.sh"

# tftp server directory.
SERVER_DIR="/var/lib/tftpboot"

sleep 3

./tftp_start.sh

expect -c "
    set timeout 30
    spawn tftp -v $RHOST

    expect \"tftp> \" 
    send \"put $TMP_FILE\r\"

    sleep 3
    expect {
        \"Transfer timed out\" { exit 1; }
        \"tftp> \" {send \"q\r\"; sleep 2;}
    }
    expect eof
"

NUM1=`ls -l $TMP_FILE | awk '{print $5}'`
NUM2=`${RSH} -n -l root $RHOST ls -l ${SERVER_DIR}/$TMP_FILE | awk '{print $5}'`
if [ -n $NUM1 ] && [ -n $NUM2 ] && [ $NUM1 = $NUM2 ];then
    echo "TPASS | tftp upload testcase."
else
    echo "TFAIL | tftp upload testcase."
    RC=1
fi

expect -c "
    set timeout 30
    spawn tftp -v $RHOST

    expect \"tftp>\"
    send \"get $TMP_FILE ${TMP_DIR}/tftp_download\r\"

    sleep 3
    expect {
        \"Transfer timed out\" { exit 1; }
        \"tftp> \" {send \"q\r\"; sleep 2;}
    }
    expect eof
"

NUM1=`ls ${TMP_DIR}/tftp_download -l | awk '{print $5}'`
NUM2=`${RSH} -n -l root $RHOST ls -l ${SERVER_DIR}/$TMP_FILE | awk '{print $5}'`
if [ -n $NUM1 ] && [ -n $NUM2 ] && [ $NUM1 = $NUM2 ];then
    echo "TPASS | tftp download testcase."
else
    echo "TFAIL | tftp download testcase."
    RC=$((RC+1))
fi

rm -rf $TMP_DIR 
${RSH} -n -l root $RHOST "rm -f ${SERVER_DIR}/${TMP_FILE}"

./tftp_stop.sh

exit $RC
